const Router = require('koa-router')
const login = new Router()
const bodyparser = require('koa-body')
const jwt = require('jsonwebtoken')
const db = require('../mysql/index');

// var gamelist
//
// db.query(`SELECT game.G_NAME "gamename",game.G_COVER "url",game.G_DESC "gamedesc" FROM game`,function(result){
//     gamelist = result
// })

login.use(bodyparser())

login.post('/', async (ctx)=>{
    let myaccount = ctx.request.body.username
    let mypwd = ctx.request.body.userpwd
    let mytoken =  await new Promise((resolve, reject) => {
        jwt.sign({ myaccount },'secret', {expiresIn: 86400},(err,token)=>{
            resolve(token)
        })
    })
    let pwd = await new Promise((resolve, reject) => {
        return db.query(`SELECT * FROM users WHERE user_name = '${myaccount}'`, [],(data) => {
            resolve(data[0])
            console.log(data[0])
        })
    })
    if (!pwd.USER_HEADER){
        pwd.USER_HEADER = 'header/default.png'
    }
    if (mypwd===pwd.USER_PWD){
        ctx.body = {
            token: mytoken,
            userid: pwd.USER_ID,
            username: myaccount,
            header: 'http://localhost:5000/' + pwd.USER_HEADER,
            userdesc: pwd.USER_DESC
        }
    }else {
        ctx.body = {
            token: '',
        }
    }

})

login.post('/register', async (ctx)=>{
    let username = ctx.request.body.username
    let email = ctx.request.body.useremail
    let pwd = ctx.request.body.password
    let now = (new Date()).Format("yyyyMMdd")
    const sql =`INSERT INTO users (USER_NAME,USER_PWD,USER_EMAIL,USER_TIME) VALUES ('${username}','${pwd}','${email}',${now});`
    console.log(sql)
    db.query(sql,[],(res,err)=>{
        console.log(res,err)
    })
    ctx.body = await new Promise((resolve, reject) => {
        return db.query(`SELECT * FROM users`,[], (data) => {
            resolve(data)
        })
    })
})


login.post('/verify', async (ctx)=>{
    let token = ctx.request.body.token
    jwt.verify(token,'secret', (err, payload)=>{
        if (err){
            ctx.response.status = 403
        }else {
            ctx.body = {
                msg: '成功'
            }
        }
    })
})


module.exports = login
